package com.qf.dao.impl;

import com.qf.dao.AdminDao;
import com.qf.pojo.Admin;
import com.qf.pojo.User;
import com.qf.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Kuke
 * @date 2021/8/30
 * 管理员接口实现层
 */
public class AdminDaoImpl implements AdminDao {
    @Override
    public Admin findAdminByName(String name) {
        try {
            //创建QueryRunner对象
            QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()) ;
            //sql
            String sql = "select * from admin where adminname = ?" ;
            Admin admin = qr.query(sql, new BeanHandler<Admin>(Admin.class), name);
            return  admin;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询用户全部数据
     * @return 返回用户列表
     */
    @Override
    public List<User> selectUserAll() {
        //执行对象
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()) ;
        //sql
        String sql = "select * from user " ;

        try {
            List<User> list = qr.query(sql, new BeanListHandler<User>(User.class));
            return list ;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 数据接口:根据用户id获取用户实体
     * @param uid  用户id号
     * @return  返回用户
     */
    @Override
    public User selectUserByUid(String uid) {
        //执行对象
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()) ;
        //sql
        String sql = "select * from user where uid = ?" ;
        //查询
        try {
            User user = qr.query(sql, new BeanHandler<User>(User.class), uid);
            return user ;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 修改用户
     * @param user 用户实体
     * @return 返回实际影响的行数
     */
    @Override
    public int updateUser(User user) {
        //执行对象
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()) ;
        //sql
        String sql = "update user set username=?,password=?,name=?,sex =? ,birthday=? ,state=? where uid  =?" ;

        //更新
        int count = 0;
        try {
            count = qr.update(sql, user.getUsername(),
                    user.getPassword(),
                    user.getName()
                    , user.getSex(),
                    user.getBirthday(),
                    user.getState(),
                    user.getUid());
            return count ;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
